import { defineStore } from 'pinia';
import { textItem } from '@/types/data'
import request from "@/untils/request";
import { ElMessage } from 'element-plus';

const editorStore = defineStore('editor', {
	state() {
		return {
			text: '' as string,
			list: [] as textItem[],
			showList: false as boolean,
			nowTextId: null as null | number,
		}
	},
	actions: {
		async saveText(user_id: number) {
			const reg = /#.*?\n/;
			const res = reg.exec(this.text);
			let title = null;
			if (res) title = res[0];
			if (this.text[0] !== '#' || this.text[1] !== ' ' || title === null) {
				ElMessage.error('标题应以\"#\"开头，以回车结尾。此外，\"#\"与标题正文间要以空格隔开');
				return;
			}
			let i = 1;
			while (title[i] === ' ') i++;
			title = title.substring(i);
			title.replaceAll("(\n|\r|(\r\n)|(\u0085)|(\u2028)|(\u2029))", "");
			if (title.length > 50) {
				ElMessage.error('标题必须小于50字');
				return;
			}
			if (this.nowTextId === null) {
				request.post('/edit/save', {
					title,
					user_id,
					text_content: this.text,
				}).then((res: any) => {
					if (res.data.code === 500) ElMessage.error(res.data.message);
					else {
						ElMessage.success('保存成功');
						this.selectText(res.data.text_id);
					}
				}).catch((err) => {
					ElMessage.error('网络错误');
				});
			} else {
				request.patch('/edit/update', {
					title,
					text_id: this.nowTextId,
					text_content: this.text,
				}).then((res: any) => {
					if (res.data.code === 500) ElMessage.error(res.data.message);
					else ElMessage.success('保存成功');
				}).catch((err) => {
					ElMessage.error('网络错误');
				});
			}
		},
		async getAllText(user_id: number) {
			request.get('/edit/query', {
				params: {
					user_id: user_id,
				}
			}).then((res) => {
				if (res.data.code === 500) {
					ElMessage.error('获取出错');
					return;
				}
				let tl: any[] = res.data.texts;
				this.list = tl.map((item: any) => {
					return {
						id: item.text_id,
						title: item.title,
						content: item.text_content,
						date: item.date,
					} as textItem;
				});
			}).catch((err) => {
				ElMessage.error('网络错误');
			});
		},
		selectText(id: number, idx: number = -1) {
			this.nowTextId = id;
			if (idx !== -1)
				this.text = this.list[idx].content;
		}
	}
});

export default editorStore;
